package com.hovhanna.monopoly.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.hovhanna.monopoly.observers.ModelObserver;


public abstract class Model<E extends Enum<E>> {
    private Map<E, Collection<ModelObserver<E>>> observers = 
                    new HashMap<E, Collection<ModelObserver<E>>>();
    
    public synchronized void subscribe(E event, ModelObserver<E> observer) {
        Collection<ModelObserver<E>> collection = observers.get(event);
        if (collection == null) {
            collection = new ArrayList<ModelObserver<E>>();
            observers.put(event, collection);
        }
        collection.add(observer);
    }
    
    public synchronized void unsubscribe(E event, ModelObserver<E> observer) {
        Collection<ModelObserver<E>> collection = observers.get(event);
        if (collection != null) {
            collection.remove(observer);
            if (collection.isEmpty()) {
                observers.remove(event);
            }
        }
    }
    
    public synchronized void publish(E event) {
        Collection<ModelObserver<E>> collection = observers.get(event);
        for (ModelObserver<E> observer : collection) {
            observer.onEvent(event, this);
        }
    }
    
    public static enum DefaultEvents {
        UPDATE;
    }
}
